#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
struct URLInfo{
	char *url;
	char *daomin;
	uint32_t domain_len;
	char *uri;
	uint32_t uri_len;
};
char *striphttp(char *url)
{
	char *http="http";
	char *https="https";
	int http_len=strlen(http);
	int https_len=strlen(https);
	if(0==strncasecmp(http,url,http_len)){
		return &url[http_len];
	}else if(0==strncasecmp(https,url,https_len)){
		return &url[https_len];
	}
	return url;
}
char *strtolower(char *url)
{
	char *ptr=url;
	while(*ptr){
		int c=*ptr;
		if(c>='A'&&c<='Z'){
			*ptr=c+'a'-'A';
		}
		ptr++;
	}
	return url;
}
void extract_urlinfo(struct URLInfo *info,char *url)
{
	char *ptr=url;
	int len=0;
	info->domain=url;
	while(*ptr){
		len++;
		if(*ptr=='/'){
			len--;
			info->domain_len=len;
			break;
		}
		ptr++;
	}
	info->uri=url+info->domain_len;
	if(*ptr==0){
		info->domain_len=len;
		info->url_len=0;
		return;
	}
	len=0;
	while(*ptr++){
		len++;
	}
	info->url_len=len;
}
int get_port_from_domain(char *domain,int domain_len)
{
	int port=80;
	int v=0;
	char *ptr=domain;
	char *end=domain+domain_len;
	while(*ptr!=':'&&ptr<end){
		ptr++;
	}
	if(':'==*ptr++){
		char c=domain[domain_len];
		domain[domain_len]=0;
		v=atoi(ptr);
		domain[domain_len]=c;
		if(v>0&&v<65535){
			return v;
		}
	}else{
		return port;
	}
}
int compareURI(struct URLInfo *a,struct URLInfo *b)
{
	char *stra=a->uri;
	int alen=a->uri_len;
	char *strb=b->uri;
	int blen=b->uri_len;
	int maxlen=alen>blen?blen:alen;
	while(maxlen>0){
		maxlen--;
		if(*stra!=*strb){
			break;
		}
		stra++;
		strb++;
	}
	return *stra-*strb;
}
int compareDomain(struct URLInfo *a,struct URLInfo *b)
{
	char *stra=a->domain;
	int alen=a->domain_len;
	char *strb=b->domain;
	int blen=b->domain_len;
	int maxlen=alen>blen?blen:alen;
	stra+=alen-1;
	strb+=blen-1;
	while(maxlen>0){
		maxlen--;
		if(*stra!=*strb){
			break;
		}
		stra--;
		strb--;
	}
	if(0==maxlen){
		if(blen>alen&&'.'==*strb){
			return 0;
		}else{
			return alen-blen;
		}

	}
	return *stra-*strb;
}
int strcmpurl(struct URLInfo *a,struct URLInfo *b)
{
	int result=0;
	result=compareDomain(a,b);
	if(0==result){
		result=compreURI(a,b);
	}
	return result;
}


